package com.gitee.limaozhi.socket.lesson02.example1;

import com.gitee.limaozhi.util.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 粘包拆包
 *
 * @author hzlimaozhi
 * @date 2019/08/07 08:32
 */
public class Server {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            // 创建套接字、绑定本地地址、监听
            serverSocket = new ServerSocket(8000);
            System.out.println("服务器：启动");

            while (true) {
                // 接受连接
                Socket socket = serverSocket.accept();
                System.out.println("\n服务器：接受连接：" + socket.getRemoteSocketAddress().toString());

                // 读写通道
                InputStream inputStream = socket.getInputStream();

                // 读取客户端
                byte[] bytes = new byte[128];
                while (true) {
                    Utils.sleepSeconds(1);
                    int count = inputStream.read(bytes);
                    if (count == -1) {
                        // 客户端关闭写通道：半关闭
                        socket.shutdownInput();
                        break;
                    }
                    System.out.println("客户端：" + new String(bytes, 0, count));
                }
                // 关闭写通道：全关闭
                socket.shutdownOutput();

                // 关闭套接字
                socket.close();
                System.out.println("客户端：关闭");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                    System.out.println("服务器：关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
